package util.bio.parsers;

import java.io.*;
import java.util.*;

import util.bio.annotation.ExonIntron;
import util.gen.IO;

/**Collapses transcripts into consensus gene merging those with the same name from a UCSC table.*/
public class MergeUCSCGeneLines {

	/**Download ensembl gene table from UCSC and replace the ENST name column with the name2.*/
	public static void main(String[] args) {
		UCSCGeneModelTableReader reader = new UCSCGeneModelTableReader (new File (args[0]), 0);
		UCSCGeneLine[] lines = reader.getGeneLines();
		
		HashMap<String,UCSCGeneLine> genes = new HashMap<String,UCSCGeneLine>();
		
		//merge
		for (int i=0; i< lines.length; i++){
			//System.out.println(lines[i].exonsToString());
			//does it exist
			if (genes.containsKey(lines[i].getName())){
				//merge exons
				UCSCGeneLine old = genes.get(lines[i].getName());
				ExonIntron[] merged = ExonIntron.mergeExonIntrons(old.getExons(), lines[i].getExons());
				old.setExons(merged);
				//reset tx start and stop
				if (old.getTxStart() > lines[i].getTxStart()) old.setTxStart(lines[i].getTxStart());
				if (old.getTxEnd() < lines[i].getTxEnd()) old.setTxEnd(lines[i].getTxEnd());
				//reset cds start stop
				if (old.getCdsStart() > lines[i].getCdsStart()) old.setCdsStart(lines[i].getCdsStart());
				if (old.getCdsEnd() < lines[i].getCdsEnd()) old.setCdsEnd(lines[i].getCdsEnd());
			}
			else genes.put(lines[i].getName(), lines[i]);
		}
		
		//print
		Iterator<String> it = genes.keySet().iterator();
		while (it.hasNext()){
			//System.out.println(genes.get(it.next()).exonsToString());
			System.out.println(genes.get(it.next()));
		}

	}

}
